package storager

import (
	"context"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gfile"
	"strings"
	"time"
)

type (
	// LocalDrive 本地上传驱动
	LocalDrive struct {
		config *LocalConfig
	}
)

func NewLocalDrive(config *LocalConfig) *LocalDrive {
	if config == nil {
		config = &LocalConfig{}
	}
	if config.Path == "" {
		config.Path = "temp/uploads"
	}
	return &LocalDrive{config}
}

func (d *LocalDrive) Upload(ctx context.Context, file *ghttp.UploadFile) (obj *FileObject, err error) {
	tempDir := gfile.Temp("gf_upload_temp")
	tempName, err := file.Save(tempDir, true)
	if err != nil {
		return nil, err
	}
	tempPath := gfile.Join(tempDir, tempName)
	defer func() {
		_ = gfile.RemoveFile(tempPath)
	}()

	obj = &FileObject{
		Meta: &FileMeta{},
	}
	// 计算文件md5
	obj.Meta.Md5, err = CalcFileMd5(tempPath)
	if err != nil {
		return nil, err
	}
	if err = hasContentMd5(ctx, obj.Meta.Md5); err != nil {
		return nil, err
	}

	var (
		ext     = Ext(file.Filename)
		nowDate = time.Now().Format("2006/01/02")
	)
	// 不含静态文件夹的路径
	fullPath := strings.Join([]string{nowDate, obj.Meta.Md5 + ext}, "/")
	// 移动到存储路径
	if err = gfile.CopyFile(tempPath, gfile.Join(d.config.Path, fullPath)); err != nil {
		return nil, err
	}
	obj.Key = "uploads/" + fullPath
	return
}

func (d *LocalDrive) Destroy(ctx context.Context, key string) error {
	key = strings.Trim(key, "uploads/")
	fullPath := gfile.Join(d.config.Path, key)
	if gfile.Exists(fullPath) {
		return gfile.RemoveFile(fullPath)
	}
	return nil
}

func (d *LocalDrive) Location(ctx context.Context, key string) string {
	var (
		scheme = "http://"
		r      = ghttp.RequestFromCtx(ctx)
		proto  = r.Header.Get("X-Forwarded-Proto")
		path   = strings.Trim(key, "/")
	)
	if r.TLS != nil || proto == "https" {
		scheme = "https://"
	}
	return scheme + r.Host + "/" + path
}
